package com.mediacenter.adapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.mediacenter.R;
import com.mediacenter.activity.ListActivity;
import com.mediacenter.application.MApplication;
import com.mediacenter.site.model.Show;
import com.naduolai.android.util.CacheUtil;

public class ContentShowAdapter extends BaseAdapter {

	private List<Show> mShows;
	private Activity mActivity;
	private GridView mGridView;
	private ExecutorService executorService;
	private Map<String, Bitmap> mCaches = new HashMap<String, Bitmap>();

	public ContentShowAdapter(Activity activity, GridView gridView) {
		mActivity = activity;
		mGridView = gridView;
	}

	public void setShows(List<Show> mShows) {
		this.mShows = mShows;
	}

	public List<Show> getShows() {
		return mShows;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(mActivity);
		convertView = inflater.inflate(R.layout.gridview_item, null);
		ImageView gridviewItemImage = (ImageView) convertView.findViewById(R.id.gridview_item_image);
		TextView gridviewItemText = (TextView) convertView.findViewById(R.id.gridview_item_text);
		final Show show = mShows.get(position);
		gridviewItemImage.setTag(show.getThumb());
		Bitmap imageBitmap = mCaches.get(show.getThumb());
		gridviewItemImage.setImageBitmap(MApplication.getInstance().findCurrentSource(show.getSourceName()) == null ? null : MApplication.getInstance().findCurrentSource(show.getSourceName()).getFace());
		if (imageBitmap != null && !imageBitmap.isRecycled()) {
			gridviewItemImage.setImageBitmap(imageBitmap);
			mCaches.put(show.getThumb(), imageBitmap);
			// android.util.Log.e(getClass().getName(), "从内存缓存中获取图片。。。");
		} else if (show.getThumb() != null) {
			Bitmap bitmap = BitmapFactory.decodeFile(CacheUtil.getLocalPath(show.getThumb()));
			if (bitmap != null) {
				bitmap = scaleMidCutBitmap(bitmap, 140, 201);
				gridviewItemImage.setImageBitmap(bitmap);
				mCaches.put(show.getThumb(), bitmap);
				// android.util.Log.e(getClass().getName(),
				// "从sdcard缓存中获取图片。。。");
			} else {
				Thread downloadImageThread = new Thread() {
					public void run() {
						try {
							CacheUtil.urlBinaryFileCopyForce(show.getThumb());
							mActivity.runOnUiThread(new Runnable() {
								public void run() {
									ImageView thisImageView = ListActivity.findImageViewByStringTag(mGridView, show.getThumb());
									Bitmap bitmap = BitmapFactory.decodeFile(CacheUtil.getLocalPath(show.getThumb()));
									if (thisImageView == null || bitmap == null) {
										return;
									}
									bitmap = scaleMidCutBitmap(bitmap, 150, 217);
									thisImageView.setImageBitmap(bitmap);
									mCaches.put(show.getThumb(), bitmap);
								}
							});
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				};
				downloadImageThread.setPriority(Thread.MIN_PRIORITY);
				if (executorService == null || executorService.isShutdown()) {
					executorService = Executors.newSingleThreadExecutor();
				}
				executorService.submit(downloadImageThread);
				// android.util.Log.e(getClass().getName(), "从网络获取图片。。。");
			}
		} else if (show.getFace() != null) {
			gridviewItemImage.setImageBitmap(show.getFace());
		}
		gridviewItemText.setText(show.getTitle() != null && show.getTitle().length() > 6 ? show.getTitle().substring(0, 6) : show.getTitle());
		return convertView;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public Object getItem(int position) {
		return mShows == null ? null : mShows.get(position);
	}

	@Override
	public int getCount() {
		return mShows == null ? 0 : mShows.size();
	}

	public void shutdownExecutorService() {
		if (executorService != null && !executorService.isShutdown()) {
			executorService.shutdownNow();
		}
	}

	public void cleanCache() {
		List<String> keys = new ArrayList<String>();
		for (String key : mCaches.keySet()) {
			Bitmap bitmap = mCaches.get(key);
			if (mGridView == null) {
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
				}
				keys.add(key);
			} else {
				ImageView imageView = ListActivity.findImageViewByStringTag(mGridView, key);
				if (imageView == null) {
					if (bitmap != null && !bitmap.isRecycled()) {
						bitmap.recycle();
					}
					keys.add(key);
				}
			}
		}
		for (int i = keys.size() - 1; i >= 0; i--) {
			mCaches.remove(keys.get(i));
		}
	}

	/**
	 * 将图片等比缩放到一定的区域
	 * 
	 * @param srcBitmap
	 * @param newWidth
	 * @param newHeight
	 * @param nagetive
	 *            true取大边false取小边
	 * @return
	 */
	public static Bitmap bitmapRoom(Bitmap srcBitmap, int newWidth, int newHeight, boolean nagetive) {
		int srcWidth = srcBitmap.getWidth();
		int srcHeight = srcBitmap.getHeight();
		double scaleWidth = ((double) newWidth) / srcWidth;
		double scaleHeight = ((double) newHeight) / srcHeight;
		boolean compare = scaleWidth < scaleHeight;
		compare = nagetive ? !compare : compare;
		scaleWidth = compare ? scaleWidth : scaleHeight;
		scaleHeight = compare ? scaleWidth : scaleHeight;
		Bitmap resizedBitmap = Bitmap.createScaledBitmap(srcBitmap, !compare ? (int) (srcWidth * scaleWidth) : newWidth, !compare ? newHeight : (int) (srcHeight * scaleHeight), true);
		if (resizedBitmap != null) {
			return resizedBitmap;
		} else {
			return srcBitmap;
		}
	}

	public static Bitmap scaleMidCutBitmap(Bitmap srcBitmap, int newWidth, int newHeight) {
		Bitmap resizedBitmap = bitmapRoom(srcBitmap, newWidth, newHeight, true);
		if (resizedBitmap.getWidth() >= newWidth) {
			return Bitmap.createBitmap(resizedBitmap, (resizedBitmap.getWidth() - newWidth) / 2, 0, newWidth, newHeight);
		} else if (resizedBitmap.getHeight() >= newHeight) {
			return Bitmap.createBitmap(resizedBitmap, 0, (resizedBitmap.getHeight() - newHeight) / 2, newWidth, newHeight);
		}
		return resizedBitmap;
	}
}
